import store from '@/store/index.js'
const loginWhiteList = ['/pages/login/index']

export function checkPermission(url) {
  const path = url.split('?')[0]
  const isLogin = store.getters.isLogin
  const isToLogin = path.includes('/pages/login/index')  || path === '/'  // 空白路径也指向登录页
  // 已登录但访问登录页 → 强制跳首页
  if (isToLogin&& isLogin) {
    uni.redirectTo({ url: '/pages/dashboard/index' })
    return false
  }

  // 未登录且不是白名单 → 跳登录
  if (!isLogin && !loginWhiteList.includes(path)) {
    // 保存被拦截路径
    uni.setStorageSync('REDIRECT_PATH', url)
    console.log('[拦截保存路径] =>', url)

    uni.showToast({ title: '请先登录', icon: 'none' })
    setTimeout(() => {
      uni.redirectTo({ url: '/pages/login/index' })
    }, 300)
    return false
  }

  return true
}

// 支持 navigateTo / redirectTo / reLaunch
['navigateTo', 'redirectTo', 'reLaunch'].forEach(method => {
  uni.addInterceptor(method, {
    invoke(args) {
      return checkPermission(args.url)
    }
  })
})

//  拦截路由 对H5页面 浏览器得前进后退不会进入上面得验证逻辑 所以单独进行权限控制
window.addEventListener('popstate', () => {
    const path = location.pathname + location.search
    checkPermission(path)
  })

